package com.luis.toolsuite.util;

import com.luis.toolsuite.kmeans.model.KmeansDataPoint;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class KMeansUtil {

    public static final int SEED = 2;
    public static final int ITERATION_NUM = 100;

    public static BigDecimal calculateDistance(Double[] p1, Double[] p2){
        BigDecimal result = BigDecimal.ZERO;
        if(p1 == null || p2 == null || p1.length != p2.length)
            return result;

        for(int i = 0; i< p1.length;i++){
            result = result.add(BigDecimal.valueOf(Math.pow((p1[i] - p2[i]),2)));
        }
        return result;
    }

    public static Double[] calculateMeanCenter(List<Double[]> clusterData){
        int dataSize = clusterData.size();
        int pointLen = clusterData.get(0).length;
        Double[] result2 = new Double[pointLen];
        Arrays.fill(result2, 0d);
        for(int i=0; i< pointLen;i++){
            for(Double[] point : clusterData){
                result2[i] += point[i];
            }
            result2[i] = result2[i] / dataSize;
        }
        return result2;
    }

    public static boolean centerEqual(List<Double[]> center1, List<Double[]> center2){
        if(center1.size() != center2.size()) return false;
        for(Double[] d1 : center1){
            boolean d1Found = false;
            for(Double[] d2 : center2){
                if(Arrays.equals(d1,d2)){
                    d1Found = true;
                    break;
                }
            }
            if(!d1Found) return false;
        }
        return true;
    }

    public static List<Double[]> convertObjectToPoint(Iterable<KmeansDataPoint> iter){
        List<Double[]> resultList = new ArrayList<>();
        iter.forEach(obj ->{
            Double[] d = new Double[2];
            d[0] = obj.getValue();
            d[1] = obj.getValue2();
            resultList.add(d);
        });
        return resultList;
    }

    public static void main(String[] args) {
        List<Double[]> l1 = new ArrayList<>();
        l1.add(new Double[]{3d,3d});
        l1.add(new Double[]{1d,2d});

        List<Double[]> l2 = new ArrayList<>();
        l2.add(new Double[]{1d,2d});
        l2.add(new Double[]{3d,3d});

        System.out.println(centerEqual(l1,l2));
    }
}
